// editOrder.js

import to_page from '../../../commons/pageaddress.js'
import api from '../../../requests/api.js'
var util = require('../../../utils/util.js')
var pingpp = require('../../../utils/pingpp.js')
var pay = require('../../../requests/pay.js')
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    maskDisplay: "none",
    // 订单结算收货地址
    address: null,
    // 订单结算数据
    orderData: {},
    // 促销弹窗使用的数据
    promotionProductInfoVo: {},
    remark: '',
    totalAmount: 0.00,
    productItemId: '',
    productQty: '',
    giftCardArray: {},
    giftCardAmount: 0.00,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    new app.WeToast();
    if (options.productId) {
      var params = {
        "productItemId": options.productId,
        "productQty": options.productQty
      }
      this.setData({
        "productItemId": options.productId,
        "productQty": options.productQty
      })
      this.getSettleBuyNow(params)

    } else {
      this.getSettle()
    }
  },
  //立即购买
  getSettleBuyNow: function(params) {
    const that = this
    api.getSettleBuyNow(params, (data) => {
      console.log(data);
      var obj = data.data.shippingInfo;
      // obj.receiverMobilee = util.formatPhone(obj.receiverMobile);
      var totalAmount = 0.0;
      // 订单vo
      var orderSettleResponseVo = data.data.orderSettleResponseVo;

      totalAmount = orderSettleResponseVo.paidAmount
      if (typeof orderSettleResponseVo.fullDecreasePromotionDeduction == 'number' && orderSettleResponseVo.fullDecreasePromotionDeduction != 0) {
        orderSettleResponseVo.orderDeduction = orderSettleResponseVo.fullDecreasePromotionDeduction + orderSettleResponseVo.totalOtherPromotionDeduction
        orderSettleResponseVo.useCoupon = false
        if (orderSettleResponseVo.avaliableCouponCount == 0) {
          orderSettleResponseVo.deductionName = "您有0张可用的优惠券"
        }
      } else if (orderSettleResponseVo.avaliableCouponCount != 0) {
        orderSettleResponseVo.orderDeduction = orderSettleResponseVo.deduction + orderSettleResponseVo.totalOtherPromotionDeduction
        orderSettleResponseVo.useCoupon = true
      } else {
        orderSettleResponseVo.orderDeduction = 0 + orderSettleResponseVo.totalOtherPromotionDeduction
        orderSettleResponseVo.deductionName = "您有0张可用的优惠券"
        orderSettleResponseVo.useCoupon = false
      }
      orderSettleResponseVo.giftCardName = '您有' + orderSettleResponseVo.availableGiftCardCount + '张礼品卡可用'
      var timestamp = new Date().getTime()
      this.setData({
        'orderData.orderSettleResultVo': orderSettleResponseVo,
        totalAmount: totalAmount.toFixed(2),
        orderToken: timestamp,
        address: obj
      })
    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }

    }, () => {

    });

  },
  getSettle: function() {
    // 订单结算数据初始化
    api.settle((data) => {
      console.log(data);
      var obj = data.data.shippingInfo;
      // obj.receiverMobilee = util.formatPhone(obj.receiverMobile);
      var totalAmount = 0.0;
      // 订单vo
      var orderSettleResponseVo = data.data.orderSettleResponseVo;

      totalAmount = orderSettleResponseVo.paidAmount
      if (typeof orderSettleResponseVo.fullDecreasePromotionDeduction == 'number' && orderSettleResponseVo.fullDecreasePromotionDeduction != 0) {
        orderSettleResponseVo.orderDeduction = orderSettleResponseVo.fullDecreasePromotionDeduction + orderSettleResponseVo.totalOtherPromotionDeduction
        orderSettleResponseVo.useCoupon = false
        if (orderSettleResponseVo.avaliableCouponCount == 0) {
          orderSettleResponseVo.deductionName = "您有0张可用的优惠券"
        }
      } else if (orderSettleResponseVo.avaliableCouponCount != 0) {
        orderSettleResponseVo.orderDeduction = orderSettleResponseVo.deduction + orderSettleResponseVo.totalOtherPromotionDeduction
        orderSettleResponseVo.useCoupon = true
      } else {
        orderSettleResponseVo.orderDeduction = 0 + orderSettleResponseVo.totalOtherPromotionDeduction
        orderSettleResponseVo.deductionName = "您有0张可用的优惠券"
        orderSettleResponseVo.useCoupon = false
      }
      orderSettleResponseVo.giftCardName = '您有' + orderSettleResponseVo.availableGiftCardCount + '张礼品卡可用'
      var timestamp = new Date().getTime()
      this.setData({
        'orderData.orderSettleResultVo': orderSettleResponseVo,
        totalAmount: totalAmount.toFixed(2),
        orderToken: timestamp,
        address: obj
      })

    }, (error) => {
      if (util.alertNetworkError(error)) {
        this.wetoast.toast({
          title: error.resMsg,
        })
      }
    }, (data) => {})
  },
  /**
   * 当页面滑动到底部时触发的方法,删掉这个方法后控制台会报事件警告
   */
  onReachBottom: function() {},

  /**
   * 拨打客服电话
   */
  callService: function() {
    var csPhone = wx.getStorageSync('csPhone')
    wx.makePhoneCall({
      phoneNumber: csPhone,
    })
  },

  /**
   * 选择收货地址
   */
  selectAddress: function() {
    var url = to_page.t + to_page.goAddressList + "?selectable=true";
    to_page.to(url)

  },

  /**
   * 选择优惠券
   */
  onCouponCheck: function(event) {
    var nData = this.data.orderData
    if (nData.orderSettleResultVo.deduction == 0) {
      this.onCouponClick(event)
    } else {
      nData.orderSettleResultVo.useCoupon = true
      nData.orderSettleResultVo.orderDeduction = nData.orderSettleResultVo.deduction + nData.orderSettleResultVo.totalOtherPromotionDeduction
      this.setData({
        orderData: nData
      })
      this.resetAmount()
    }
  },

  /**
   * 选择促销优惠
   */
  onPromotionCheck: function(event) {
    var nData = this.data.orderData
    nData.orderSettleResultVo.useCoupon = false
    nData.orderSettleResultVo.orderDeduction = nData.orderSettleResultVo.fullDecreasePromotionDeduction + nData.orderSettleResultVo.totalOtherPromotionDeduction
    this.setData({
      orderData: nData
    })
    this.resetAmount()
  },
  //选择礼品卡
  onGiftCardCheck: function() {
    var nGiftCardAmount = this.data.giftCardAmount
    var nData = this.data.orderData
    nData.orderSettleResultVo.useGiftCard = false
    nData.orderSettleResultVo.giftCardName = '您有' + nData.orderSettleResultVo.availableGiftCardCount + '张礼品卡可用'
    nGiftCardAmount = 0.0
    this.setData({
      orderData: nData,
      giftCardAmount: nGiftCardAmount,
      giftCardArray: []
    })
    this.resetAmount()
  },

  /**
   * 选择订单可用优惠券
   */
  onCouponClick: function(event) {
    wx.navigateTo({
      url: '../../preferential/coupon?entrance=buyCart' +
        '&couponid=' + this.data.orderData.orderSettleResultVo.endUserCouponId // 当前选中的优惠券ID 
        +
        '&isOversea=' + this.data.orderData.orderSettleResultVo.overseaOrder // 是否是海购订单
    })
  },

  /**
   * 重设订单小计和订单总价
   */
  resetAmount() {
    var nData = this.data.orderData.orderSettleResultVo
    //订单需要支付的价钱（减去优惠和礼品卡）
    var nTotalAmount = 0.0;
    //礼品卡的优惠
    var nGiftCardAmount = this.data.giftCardAmount
    //优惠券和促销只能使用一个
    if (nData.useCoupon) {
      nData.paidAmount = nData.productTotalAmount - nData.deduction - nData.totalOtherPromotionDeduction
    } else {
      nData.paidAmount = nData.productTotalAmount - nData.fullDecreasePromotionDeduction - nData.totalOtherPromotionDeduction
    }
    //计算运费逻辑，产品总金额减去优惠总金额，判断下是否需要增加运费
    nData.deliveryFee = 0
    if (nData.paidAmount < nData.deliveryFeeThreshold) {
      //如果使用的免邮优惠券，则运费为0
      if (nData.freeDeliveryFee && nData.useCoupon) {
        nData.deliveryFee = 0
      } else {
        nData.paidAmount += nData.deliveryStandard
        nData.deliveryFee = nData.deliveryStandard
      }
    }

    nTotalAmount += nData.paidAmount
    nData.paidAmount = nData.paidAmount.toFixed(2)
    //如果礼品卡抵扣的金额大于订单总金额，则礼品卡减为订单总金额。
    if (nGiftCardAmount > nTotalAmount) {
      nGiftCardAmount = nTotalAmount
    }
    //计算出总金额再减去礼品卡的金额
    nTotalAmount = nData.paidAmount - nGiftCardAmount
    this.setData({
      'orderData.orderSettleResultVo': nData,
      totalAmount: nTotalAmount.toFixed(2)
    })
  },

  //浮动球点击 侧栏展开
  promotionClickEvent: function(event) {
    this.setData({
      promotionProductInfoVos: this.data.orderData.orderSettleResultVo.promotionProductInfoVos
    })
    slideUp.call(this);
  },

  //遮罩点击  侧栏关闭
  slideCloseEvent: function() {
    slideDown.call(this);
  },

  //订单商品数>3,订单列表展开
  collapse: function(ev) {
    var nData = this.data.orderData
    nData.orderSettleResultVo.notCollapse = true

    this.setData({
      orderData: nData
    })
  },

  // 设置订单使用的优惠券
  setCoupon: function(coupon) {
    if (coupon == null) {
      this.setNotUseCoupon()
    } else {
      var nData = this.data.orderData
      nData.orderSettleResultVo.deductionName = coupon.title
      nData.orderSettleResultVo.deduction = coupon.deduction
      nData.orderSettleResultVo.orderDeduction = coupon.deduction + nData.orderSettleResultVo.totalOtherPromotionDeduction
      nData.orderSettleResultVo.endUserCouponId = coupon.id
      nData.orderSettleResultVo.useCoupon = true
      nData.orderSettleResultVo.freeDeliveryFee = coupon.freeDeliveryFee
      this.setData({
        orderData: nData
      })
      this.resetAmount()
    }
  },

  // 设置子订单不使用优惠券
  setNotUseCoupon() {
    var nData = this.data.orderData
    nData.orderSettleResultVo.deductionName = '您有' + nData.orderSettleResultVo.avaliableCouponCount + '张优惠券可用'
    nData.orderSettleResultVo.orderDeduction = nData.orderSettleResultVo.fullDecreasePromotionDeduction + nData.orderSettleResultVo.totalOtherPromotionDeduction
    nData.orderSettleResultVo.deduction = 0
    nData.orderSettleResultVo.endUserCouponId = 0
    nData.orderSettleResultVo.useCoupon = false
    //是否使用免邮优惠券
    nData.orderSettleResultVo.freeDeliveryFee = false
    this.setData({
      orderData: nData
    })
    this.resetAmount()
  },

  // 设置订单使用的礼品卡
  setGiftCard: function(giftCardArray) {
    if (giftCardArray.length > 0) {
      var giftAmount = 0.0
      for (var i = 0; i < giftCardArray.length; i++) {
        giftAmount += giftCardArray[i].giftCardAmount
      }
      this.setData({
        "giftCardArray": giftCardArray,
        "orderData.orderSettleResultVo.useGiftCard": true,
        "giftCardAmount": giftAmount
      })
    } else {
      this.setData({
        "giftCardArray": giftCardArray,
        "orderData.orderSettleResultVo.useGiftCard": false
      })
    }
    this.resetAmount()

  },

  //微信支付按钮
  wx_pay: function(e) {
    const that = this
    if (!that.data.address) {
      that.wetoast.toast({
        title: '请先选择一个收货地址',
      })
    } else {
      that.createOrder();
    }
  },

  /**
   * 创建订单
   */
  createOrder: function() {
    var nData = this.data.orderData.orderSettleResultVo
    var params = []
    var productPriceGroup = ''
    for (var j = 0; j < nData.orderSettles.length; j++) {
      productPriceGroup += nData.orderSettles[j].productId + ':' + nData.orderSettles[j].sellPrice
      if (j < nData.orderSettles.length - 1) {
        productPriceGroup += ','
      }
    }
    params = {
      oversea: nData.overseaOrder,
      remark: this.data.remark,
      orderAmount: nData.paidAmount,
      orderPaidAmount: this.data.totalAmount,
      productPriceGroup: productPriceGroup,
    }
    if (nData.useCoupon) {
      params.endUserCouponId = nData.endUserCouponId
    }
    if (this.data.productItemId) {
      params.productItemId = this.data.productItemId
      params.productQty = this.data.productQty
    }
    if (nData.useGiftCard) {
      var giftCardSettle = []
      var orderGiftAmount = this.data.giftCardAmount
      var giftCardArray = this.data.giftCardArray
      for (var i = 0; i < giftCardArray.length; i++) {
        orderGiftAmount -= giftCardArray[i].giftCardAmount
        if (orderGiftAmount >= 0) {
          giftCardSettle[i] = {
            giftCardId: giftCardArray[i].giftCardId,
            useAmount: giftCardArray[i].giftCardAmount
          }
        } else {
          giftCardSettle[i] = {
            giftCardId: giftCardArray[i].giftCardId,
            useAmount: giftCardArray[i].giftCardAmount + orderGiftAmount
          }
          break
        }
      }
      params.giftCardUseList = giftCardSettle
    }

    var systemInfo = ""

    var platformCode = 5
    try {
      systemInfo = wx.getSystemInfoSync()

      if (systemInfo.platform == "ios") {
        platformCode = 5
      } else {
        platformCode = 6
      }
    } catch (e) {

    }
    params.shippingInfoId = this.data.address.id
    params.orderSource = platformCode
    params.orderToken = this.data.orderToken

    console.log(params)
    wx.showLoading()
    api.createOrder(
      params, (res) => {
        console.log(res.data)

        this.request_charge(res.data)
      },
      (error) => {

        wx.hideLoading()
        if (util.alertNetworkError(error)) {
          this.wetoast.toast({
            title: error.resMsg,
          })
        }
      },
      (res) => {

      },
    )
  },

  // {
  //   "parentOrderId": 5904,
  //   "parentOrderCode": "4948188395",
  //   "orderResultVoList": [{
  //     "orderId": 5902,
  //     "orderCode": "7356558395"
  //   }, {
  //     "orderId": 5903,
  //     "orderCode": "2684182395"
  //   }]
  // }
  //获取支付凭证
  request_charge: function(data) {
    wx.showLoading()
    const that = this
    var orderNo
    orderNo = data.orderCode
    this.setData({
      orderCode: data.orderCode,
      singleOrder: true
    })

    if (this.data.totalAmount == 0) {
      wx.showToast({
        title: '下单已成功',
        icon: 'none'
      })
      wx.redirectTo({
        url: '../orderDetail/orderDetail?orderCode=' + that.data.orderCode,
      })
      return
    }
    ///微信支付的时候先拿缓存。看是否有openId
    wx.getStorage({
      key: 'openId',
      success: function(res) {
        if (res.data) {
          var params = {
            openId: res.data,
            orderNo: orderNo,
            channel: "wx_lite",
            clientIp: "127.0.0.1"
          };
          that.getcharge(params)
        }else {
          //调用登录接口
          wx.login({
            success: (ev) => {
              var code = ev.code
              that.code2Session(code)
            }
          })
        }
      },
      fail: function (res) {
        console.log('s:获取失败openId缓存失败')
        //调用登录接口
        wx.login({
          success: (ev) => {
            var code = ev.code
            that.code2Session(code)
          }
        })
      }
  
    })
 
  },

  code2Session: function (code) {
    var params = {
      code: code
    }
    api.post_code2Session(params, (res) => {
      console.log(res)
      if (res.data) {
        wx.setStorage({
          key: 'openId',
          data: res.data.openId
        })
        var params = {
          openId: res.data.openId,
          orderNo: this.data.orderCode,
          channel: "wx_lite",
          clientIp: "127.0.0.1"
        };
        this.getcharge(params)
      }
    }, () => {

    }, () => {

    });
  },

  getcharge: function(params) {
    pay.request_charge(params, (res) => {
      wx.hideLoading()
      wx.reportAnalytics('pay_wechat_success', {
        price: this.data.totalAmount,
        ordercode: orderNo
      })
      if (this.data.singleOrder) {
        wx.redirectTo({
          url: '../orderDetail/orderDetail?orderCode=' + this.data.orderCode,
        })
      } else {
        wx.redirectTo({
          url: '../allOrders/allOrders',
        })
      }
      wx.showToast({
        title: '支付成功',
      })
    }, (res) => {
      wx.hideLoading()
      if (this.data.singleOrder) {
        wx.redirectTo({
          url: '../orderDetail/orderDetail?orderCode=' + this.data.orderCode,
        })
      } else {
        wx.redirectTo({
          url: '../allOrders/allOrders?index=0',
        })
      }
    });
  },

  //记录买家留言
  bindKeyInput: function(ev) {
    var nRemark = this.data.remark
    nRemark = ev.detail.value
    this.setData({
      remark: nRemark
    })
  },

  //选择礼品卡
  giftCardClickEvent: function() {
    console.log(this.data.giftCardArray)
    wx.navigateTo({
      url: '../../giftCard/selectGiftCard?orderAmount=' + this.data.orderData.orderSettleResultVo.paidAmount + '&selectArray=' + JSON.stringify(this.data.giftCardArray),
    })
  }
})

//侧栏展开
function slideUp() {
  var animation = wx.createAnimation({
    timingFunction: "ease-out",
    duration: 300
  });
  this.setData({
    maskDisplay: 'block'
  });
  animation.translateY('0%').step();
  this.setData({
    slideAnimation: animation.export()
  });


}

//侧栏关闭
function slideDown() {
  var animation = wx.createAnimation({
    duration: 300
  });
  animation.translateY('100%').step();
  this.setData({
    slideAnimation: animation.export()

  });
  this.setData({
    maskDisplay: 'none'
  });
}